using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Net;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace edu.stanford.hci.ideas
{
    class ImageUtil
    {
        public static Image GetImageFromURL(string strURL)
        {
            Image retVal = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strURL);
                request.Timeout = 5000; // 5 seconds in milliseconds
                request.ReadWriteTimeout = 20000; // allow up to 20 seconds to elapse
                // execute the request
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                retVal = Image.FromStream(response.GetResponseStream());
            }
            catch (Exception)
            {
                retVal = null;
            }
            return retVal;
        }

        public static Image ScaleToFixedSize(Image imgPhoto, int Width, int Height)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);
            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = System.Convert.ToInt16((Width -
                              (sourceWidth * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = System.Convert.ToInt16((Height -
                              (sourceHeight * nPercent)) / 2);
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width, Height,
                              PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                             imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(Color.Transparent);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
    }
}
